/**
 * 
 */
package cn.crm.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Service;

import cn.crm.bean.DDL;
import cn.crm.dao.DDLDao;
import cn.crm.service.DDLService;

/**
 * @author wbh
 * 
 */
@Service("ddlService")
public class DDLServiceImpl implements DDLService {
	@Resource
	private DDLDao ddlDao;

	@Override
	public boolean save(DDL ddl) {
		// TODO Auto-generated method stub
		return ddlDao.add(ddl) > 0;
	}

	@Override
	public boolean update(DDL ddl) {
		// TODO Auto-generated method stub
		return ddlDao.update(ddl) > 0;
	}

	@Override
	public boolean del(DDL ddl) {
		// TODO Auto-generated method stub
		return ddlDao.del(ddl) > 0;
	}

	@Override
	public String show() {
		// TODO Auto-generated method stub
		JSONArray json = new JSONArray();
		List<DDL> list = ddlDao.show();
		for (DDL ddl : list) {
			JSONObject object = new JSONObject();
			object.put("id", ddl.getTypeId());
			object.put("type", ddl.getTypeType());
			object.put("key", ddl.getTypeKey());
			object.put("value", ddl.getTypeValue());
			json.add(object);
		}
		return json.toJSONString();
	}

	@Override
	public String getByType(String type) {
		// TODO Auto-generated method stub
		JSONArray json = new JSONArray();
		List<DDL> list = ddlDao.byType(type);
		for (DDL ddl : list) {
			JSONObject object = new JSONObject();
			object.put("id", ddl.getTypeId());
			object.put("type", ddl.getTypeType());
			object.put("key", ddl.getTypeKey());
			object.put("value", ddl.getTypeValue());
			json.add(object);
		}

		return json.toJSONString();
	}

	@Override
	public DDL get(Integer id) {
		// TODO Auto-generated method stub
		return ddlDao.get(id);
	}

	/**
	 * @param ddlDao
	 *            the ddlDao to set
	 */
	public void setDdlDao(DDLDao ddlDao) {
		this.ddlDao = ddlDao;
	}

	@Override
	public String getAllType() {
		JSONArray jlist = new JSONArray();
		for (String str : ddlDao.getAllType()) {
			JSONObject obj = new JSONObject();
			obj.put("type", str);
			jlist.add(obj);
		}
		return jlist.toJSONString();
	}

	@Override
	public int getCountByType(String type) {
		// TODO Auto-generated method stub
		return  ddlDao.byType(type).size();
	}

	@Override
	public List<DDL> getListByType(String type,String def) {
		List<DDL> list=new ArrayList<DDL>();
		if (def!=null&&!def.equals("")) {
			DDL ddl=new DDL();
			ddl.setTypeId(-1);
			ddl.setTypeValue(def);
			list.add(ddl);
		}
		List<DDL> temp=ddlDao.byType(type);
		System.out.println("temp.size="+temp.size());
		if (temp!=null) {
			for (DDL ddl2 : temp) {
				list.add(ddl2);
			}
		}
		return list;
	}

	@Override
	public List<DDL> byType(String type) {
		return ddlDao.byType(type);
	}
}
